<template>
  <el-form :model="data" :rules="rules" label-width="100px">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="规程名称：" prop="name">
          <el-input v-model="data.name" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="允许误差：" prop="errorFormula">
          <div class="input-with-icon">
            <el-input v-model="data.errorFormula" />
            <el-tooltip trigger="click">
              <template #content>
                可输入公式或数字。
                <br />
                公式：检定点占位符用“x”表示，公式“1%*x+5”，若取样点=100，允许误差即±6。
                <br />
                数字：对于所有检定点，允许误差都是±该数字。
              </template>
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="检定点：" prop="points">
          <div class="mt-4" v-if="isRain">
            <el-checkbox
              @change="(checked) => handleCheckboxChange(item, checked)"
              v-for="item in checkboxRainTypes"
              :key="item.value"
              :label="item.label"
              border
            />
          </div>
          <el-input-tag
            v-model="strPointArr"
            draggable
            tag-effect="plain"
            :disabled="isRain"
            :placeholder="isRain ? `请按检定顺序勾选雨量类型。` : `请输入检定点，按“回车键”确定。`"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 雨量 -->
    <el-row v-if="isRain" :gutter="20">
      <el-col :span="12">
        <el-form-item label="读数次数：" prop="readCount">
          <el-input-number v-model="data.readCount" :min="1" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="合格判定：" prop="qualifiedJudgment">
          <el-select v-model="data.qualifiedJudgment">
            <el-option
              v-for="key in Object.keys(EnumQualifiedJudgment)"
              :key="key"
              :value="key"
              :label="EnumQualifiedJudgment[key]"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 雨量 End -->

    <!-- 气压 -->
    <div v-else-if="settingStore.elementType === ElementTypeEnum.Pressure">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="往返次数：" prop="readCount">
            <div class="input-with-icon">
              <el-input-number v-model="data.readCount" :min="1" />
              <el-tooltip content="往返1次，及正程1次加反程1次。" trigger="click">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="稳定时间：" prop="qualifiedJudgment">
            <el-input-number v-model="data.stableSeconds" :min="1">
              <template #suffix>
                <span>秒</span>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合格判定：" prop="qualifiedJudgment">
            <el-select v-model="data.qualifiedJudgment">
              <el-option
                v-for="key in Object.keys(EnumQualifiedJudgment)"
                :key="key"
                :value="key"
                :label="EnumQualifiedJudgment[key]"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <!-- 气压 End -->

    <!-- 温度、湿度 -->
    <div v-else>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="读数次数：" prop="readCount">
            <el-input-number v-model="data.readCount" :min="1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="读数间隔：" prop="readIntervalSecond">
            <el-input-number v-model="data.readIntervalSecond" :min="1">
              <template #suffix>
                <span>秒</span>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="稳定时间：" prop="stableSeconds">
            <el-input-number v-model="data.stableSeconds" :min="1">
              <template #suffix>
                <span>秒</span>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="稳定误差：" prop="stableErrorFormula">
            <div class="input-with-icon">
              <el-input v-model="data.stableErrorFormula" />
              <el-tooltip trigger="click">
                <template #content>
                  稳定时间范围内（{{
                    data.stableSeconds
                  }}秒），所有记录的标准值都在“检定点±偏移量”范围内，且标准值的公差≤稳定误差，判断为稳定。
                  <br />
                  输入规则同“允许误差”。
                </template>
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="偏移量：" prop="stableOffsetFormula">
            <div class="input-with-icon">
              <el-input v-model="data.stableOffsetFormula" />
              <el-tooltip trigger="click">
                <template #content>
                  稳定时间范围内（{{
                    data.stableSeconds
                  }}秒），所有记录的标准值都在“检定点±偏移量”范围内，且标准值的公差≤稳定误差，判断为稳定。
                  <br />
                  输入规则同“允许误差”。
                </template>
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合格判定：" prop="qualifiedJudgment">
            <el-select v-model="data.qualifiedJudgment">
              <el-option
                v-for="key in Object.keys(EnumQualifiedJudgment)"
                :key="key"
                :value="key"
                :label="EnumQualifiedJudgment[key]"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <!-- 温度、湿度 End -->

    <el-row justify="center">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleClose(false)">取消</el-button>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { Regulation } from "@/types/business/regulation";
import { QuestionFilled } from "@element-plus/icons-vue";
import {
  ElementTypeEnum,
  EnumQualifiedJudgment,
  EnumRainfallType,
  RainfallTypeDescriptions,
} from "@/enums";
import { isNumeric } from "@/utils";
import { useSettingsStore } from "@/store";
import regulationApi from "@/api/business/regulation.api";

const emit = defineEmits<{
  (e: "close", refreshTable: boolean): void;
}>();
const settingStore = useSettingsStore();
const isRain = computed(() => settingStore.elementType === ElementTypeEnum.Rain);

const props = defineProps(["formData"]);
const data = reactive<Regulation>(props.formData);
const strPointArr = ref<string[]>([]);
const checkboxRainTypes = reactive<any[]>([]);

onMounted(() => {
  data.points.forEach((item) => {
    strPointArr.value.push(item.toString());
  });
  // 雨量类型
  if (isRain.value) {
    for (const enumRainfallTypeKey in EnumRainfallType) {
      if (isNumeric(enumRainfallTypeKey)) {
        const desc = RainfallTypeDescriptions[enumRainfallTypeKey];
        checkboxRainTypes.push({ label: desc, value: enumRainfallTypeKey });
      }
    }
  }
});

// 雨量类型勾选事件
function handleCheckboxChange(item, checked) {
  if (checked) {
    strPointArr.value.push(item.label);
  } else {
    const index = strPointArr.value.indexOf(item.label);
    if (index >= 0) strPointArr.value.splice(strPointArr.value.indexOf(item.label), 1);
  }
}

function handleSave() {
  console.log("handleSave", data);
  data.points = strPointArr.value.map((item) => parseFloat(item));
  regulationApi.modifyDeviceConfig(data).then(() => {
    ElMessage.success("保存成功");
    // 关闭弹窗，刷新
    handleClose(true);
  });
}

function handleClose(refreshTable: boolean) {
  emit("close", refreshTable);
}

// region 表单校验

const rules = reactive({
  name: [{ required: true, message: "“规程名称”不能为空", trigger: "blur" }],
  errorFormula: [{ required: true, message: "“允许误差”不能为空", trigger: "blur" }],
  stableErrorFormula: [{ required: true, message: "“稳定误差”不能为空", trigger: "blur" }],
  stableOffsetFormula: [{ required: true, message: "“偏移量”不能为空", trigger: "blur" }],
});

// endregion
</script>

<style scoped lang="scss">
.input-with-icon {
  display: flex;
  align-items: center;
}

.input-with-icon .el-input {
  flex: 1;
  margin-right: 8px;
}
</style>
